<template>
  <div>
    <ReturnPage />
    <el-form :inline="true" class="demo-form-inline mt20" size="mini">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="value"
          value-format="yyyy-MM-dd hh:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search()">查询</el-button>
      </el-form-item>
    </el-form>
    <div
      v-for="(item, index) in data[3]"
      :key="index"
      class="item"
      :id="'disperse' + index"
    ></div>
    <!-- 饼图 -->
    <div
      v-for="(item, index) in data[2]"
      :key="index"
      class="item"
      :id="'pie' + index"
    ></div>
    <!-- 折线图 -->
    <div
      v-for="(item, index) in data[1]"
      :key="index"
      class="item"
      :id="'line' + index"
    ></div>
    <div
      v-for="(item, index) in data[0]"
      :key="index"
      class="item"
      :id="'normal' + index"
    ></div>
  </div>
</template>

<script>
import {
  getGraphsApi,
  getGraphsIconApi,
} from "@/api/automated/instrumentPanel";
import * as echarts from "echarts";
export default {
  data() {
    return {
      value: [],
      //查询信息参数
      getGraphQuery: {
        graphids: "",
        graphtype: "",
        startTime: "2023-10-10 00:00:00",
        endTime: "",
      },
      // 图形数据
      getGraphData: [],
      //图像信息
      data: {
        0: [],
        1: [],
        2: [],
      },
    };
  },
  created() {
    this.getGraphs();
  },
  methods: {
    //时间查询
    search() {
      this.getGraphQuery.startTime = this.value[0];
      this.getGraphQuery.endTime = this.value[1];
      this.getGraph();
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    //图表渲染
    getGraph() {
      //折线图
      this.data[1] &&
        this.data[1].forEach(async (item, index) => {
          let chartDom = document.getElementById("line" + index);
          let myChart = echarts.init(chartDom);
          let option;
          this.getGraphQuery.graphids = item.graphid;
          this.getGraphQuery.graphtype = item.graphtype;
          await this.getGraphsIcon();
          let yArr = [];
          let xArr = [];
          this.getGraphData.forEach((e, i) => {
            const obj = {
              name: e.name,
              type: "line",
              stack: "total",
              label: {
                show: true,
              },
              emphasis: {
                focus: "series",
              },
              data: [],
            };
            let dataArray = [];
            xArr = e.histories
              .map((v, i) => {
                if (i % 2 === 1) {
                  let value = Number(v.value).toFixed(1);
                  dataArray.push(value);
                  return this.timestampToTime(v.clock);
                } else {
                  return undefined; // 或者可以返回其他值，或者使用 null
                }
              })
              .filter((ele) => ele !== undefined)
              .reverse();
            obj.data = dataArray.reverse();
            yArr.push(obj);
          });

          option = {
            tooltip: {
              trigger: "axis",
            },
            legend: {},
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              data: xArr,
            },
            yAxis: {
              type: "value",
              min: (value) => {
                return value.min;
              },
              max: (value) => {
                return value.max;
              },
            },
            series: yArr,
          };

          option && myChart.setOption(option);
        });
      this.data[0] &&
        this.data[0].forEach(async (item, index) => {
          let chartDom = document.getElementById("normal" + index);
          let myChart = echarts.init(chartDom);
          let option;
          this.getGraphQuery.graphids = item.graphid;
          this.getGraphQuery.graphtype = item.graphtype;
          await this.getGraphsIcon();
          let yArr = [];
          let xArr = [];
          this.getGraphData.forEach((e, i) => {
            const obj = {
              name: e.name,
              type: "line",
              stack: "total",
              label: {
                show: true,
              },
              emphasis: {
                focus: "series",
              },
              data: [],
            };
            let dataArray = [];
            xArr = e.histories
              .map((v, i) => {
                if (i % 2 === 1) {
                  let value = Number(v.value).toFixed(1);
                  dataArray.push(value);
                  return this.timestampToTime(v.clock);
                } else {
                  return undefined; // 或者可以返回其他值，或者使用 null
                }
              })
              .filter((ele) => ele !== undefined)
              .reverse();
            obj.data = dataArray.reverse();
            yArr.push(obj);
          });

          option = {
            tooltip: {
              trigger: "axis",
            },
            legend: {},
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              containLabel: true,
            },
            xAxis: {
              type: "category",
              data: xArr,
            },
            yAxis: {
              type: "value",
              min: (value) => {
                return value.min;
              },
              max: (value) => {
                return value.max;
              },
            },
            series: yArr,
          };

          option && myChart.setOption(option);
        });
      //饼图
      this.data[2] &&
        this.data[2].forEach(async (item, index) => {
          let chartDom = document.getElementById("pie" + index);
          let myChart = echarts.init(chartDom);
          let option;
          this.getGraphQuery.graphids = item.graphid;
          this.getGraphQuery.graphtype = item.graphtype;
          await this.getGraphsIcon();
          const arr = [];
          this.getGraphData.forEach((e, i) => {
            const obj = {
              name: e.name,
              value: e.value.match(/\d+/g),
              unit: e.value.replace(/\d+/g, ""),
            };
            arr.push(obj);
          });
          option = {
            title: {
              text: item.name,
              left: "center",
            },
            tooltip: {
              trigger: "item",
              formatter: (params) => {
                const str = `${params.seriesName}<br/>${params.data.name}:${params.data.value}${params.data.unit}`;
                return str;
              },
            },
            legend: {
              orient: "vertical",
              left: "right",
            },
            series: [
              {
                name: "值",
                type: "pie",
                radius: "50%",
                data: arr,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.5)",
                  },
                },
              },
            ],
          };

          option && myChart.setOption(option);
        });
      this.data[3] &&
        this.data[3].forEach(async (item, index) => {
          let chartDom = document.getElementById("disperse" + index);
          let myChart = echarts.init(chartDom);
          let option;
          this.getGraphQuery.graphids = item.graphid;
          this.getGraphQuery.graphtype = item.graphtype;
          await this.getGraphsIcon();
          const arr = [];
          this.getGraphData.forEach((e, i) => {
            const obj = {
              name: e.name,
              value: e.value.match(/\d+/g),
              unit: e.value.replace(/\d+/g, ""),
            };
            arr.push(obj);
          });
          option = {
            title: {
              text: item.name,
              left: "center",
            },
            tooltip: {
              trigger: "item",
              formatter: (params) => {
                const str = `${params.seriesName}<br/>${params.data.name}:${params.data.value}${params.data.unit}`;
                return str;
              },
            },
            legend: {
              orient: "vertical",
              left: "right",
            },
            series: [
              {
                name: "值",
                type: "pie",
                radius: "50%",
                data: arr,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.5)",
                  },
                },
              },
            ],
          };

          option && myChart.setOption(option);
        });
    },
    //根据图表ID数据
    async getGraphsIcon() {
      let res = await getGraphsIconApi(this.getGraphQuery);
      let { code, data } = res;
      if (code == 200) {
        this.getGraphData = data;
      }
    },
    //获取主机图像信息
    async getGraphs() {
      let res = await getGraphsApi(this.$route.query.hostids);
      let { code, data } = res;
      if (code == 200) {
        this.data = data;
        this.$nextTick(() => {
          this.getGraph();
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.item {
  width: 100%;
  height: 300px;
  background-color: #fff;
  margin-bottom: 20px;
  border-radius: 10px;
}
</style>